#include <iostream>
#include <string>
#include <cerrno>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <unistd.h>

using namespace std;

int main()
{
    //1.创建管道
    int pipeid[2];
    int n = pipe(pipeid);
    if(n < 0)
    {
        cout << errno << strerror(errno) << endl;
    }
    cout << pipeid[0] << endl; //0是张嘴 就是读
    cout << pipeid[1] << endl; //1是个笔 就是写
    //2.创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0)
    {
        //3.关闭不需要的fd,父进程读取，子进程写
        close(pipeid[0]);

        //5.通信开始
        const string namestr = "hello,i am child";
        int cnt = 1;
        char buffer[1024];
        while(true)
        {
            snprintf(buffer,sizeof(buffer),"%s,my cnt = %d,myPID = %d\n",namestr.c_str(),cnt++,getpid());
            write(pipeid[1],buffer,strlen(buffer));
            sleep(1);
        }

        close(pipeid[1]);
        //让下面的代码被父进程独享
        exit(0);
    }

    //4.父进程关闭写
    close(pipeid[1]);
    

    //5.开始父子进程通信：要结合某种场景！！！！
    char buffer[1024];
    while(true)
    {
        int n = read(pipeid[0],buffer,sizeof(buffer)-1);
        //这里-1是给 \0 留位置
        cout << "没有被阻塞住" << endl;

        //cout << n << endl;
        if(n > 0)
        {
            buffer[n] = '\0';
            cout << "child send me message:" << buffer << endl;
        }
    }

    return 0;
}
